<template>
	<div class="transferFund">
		<div class="t-top">
			<el-card>
			<el-form :model="funds"  size="small" :rules="rules" ref="fundsForm" :hide-requied-aterisk="true">
				<el-form-item >
					<el-button style="color: #3A3A3A;font-size:25px;font-weight:bold;margin-left:20px" :disabled="true" type="info">公司信息</el-button>
					<span style="color: #3A3A3A;margin-left:30px;font-size:16px;">商城账号：{{account.usermobile || ""}}</span>
					<span style="color: #3A3A3A;margin-left:60px;font-size:16px;">企业名称：{{account.enterprisename || ""}}</span>
					<span style="color: #3A3A3A;margin-left:80px;font-size:16px;">社会统一信用码：{{account.registrationnumber || ""}}</span>	
				</el-form-item>
				<el-form-item>
					<el-button style="color: #3A3A3A;font-size:25px;font-weight:bold;margin-left:20px" :disabled="true" type="info">账户信息</el-button>
					<span style="color: #3A3A3A;margin-left:30px;font-size:16px;">总账户：￥{{account.usersurplusintegral }}</span>
					<span style="color: #3A3A3A;margin-left:60px;font-size:16px;">可提现账户：￥{{account.unlimitedaccount }}</span>
					<span style="color: #3A3A3A;margin-left:60px;font-size:16px;">转账账户：￥{{account.limitaccount }}</span>
					<el-button type="primary" @click="toEntityQuery" size="small" style="position:absolute;right:25%;margin-top:6px">商户查询</el-button>	
				</el-form-item>
				<el-form-item prop="type">
					<span slot="label" ></span>
					<el-button style="color: #3A3A3A;font-size:25px;font-weight:bold;" :disabled="true" type="warning">调整类型</el-button>
                    <el-radio-group v-model="funds.type">
						<el-radio :label="1" size="medium" >充值</el-radio>
                        <el-radio :label="2" size="medium">扣减</el-radio>
                    </el-radio-group>
                </el-form-item>
				<el-form-item  class="query-form-item" prop="money" :inline="true" >
					<span slot="label"></span>
					<el-button style="color: #3A3A3A;font-size:25px;font-weight:bold;" :disabled="true" type="danger">调整金额</el-button>
					<el-input v-model="funds.money" placeholder="请输入金额" @keyup.enter.native="onSubmit" clearable :maxlength="13" 
							  auto-complete="off" oninput="value=value.replace(/[^0-9.]/g,'')" style="width:20%;margin-left:30px">
						<i slot="prefix" style="font-style: normal;font-size: 16px;">￥</i>
					</el-input>
				</el-form-item>
				<el-form-item  class="query-form-item" prop="remarks">
					<span slot="label"></span>
					<el-button style="color: #3A3A3A;font-size:25px;font-weight:bold;padding:9px 40px" :disabled="true" type="success">备注</el-button>
						<el-input v-model="funds.remarks" type="textarea"  placeholder="请输入备注" prefix-icon="el-icon-search"
						@keyup.enter.native="onSubmit" clearable style="width:25%;margin-left:30px"></el-input>	
					<el-button type="primary" @click="editFundRule('fundsForm')" size="small" style="position:absolute;right:25%;margin-top:6px">账户调整</el-button>
				</el-form-item>
				<!-- 查询框 -->
				<!-- <el-form-item>
					<div style="text-align:center">
						
					</div>
				</el-form-item> -->
			</el-form>
			</el-card>
		</div>

		<!-- <div class="zjTitle">资金调整历史记录</div> -->
		<div style="margin-top:30px">
		<el-form :inline="true" :model="query" label-width="130px" size="small">
			<!-- 申请申请ID查询 -->
			<el-form-item label="商城账号：" class="query-form-item">
				<el-input v-model="query.usermobile" placeholder="请输入账号" prefix-icon="el-icon-search"
					@keyup.enter.native="onSubmit" clearable></el-input>
			</el-form-item>
			<!-- 申请公司名称查询 -->
			<el-form-item label="商城企业名称：" class="query-form-item">
				<el-input v-model="query.enterprisename" placeholder="请输入公司名称" prefix-icon="el-icon-search"
					@keyup.enter.native="onSubmit" clearable></el-input>
			</el-form-item>
			<!-- 申请生成时间 -->
			<el-form-item label="调整时间：">
				<el-date-picker v-model="createTime" unlink-panels type="datetimerange" :picker-options="pickerOptions"
					range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" align="left"
					format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
					:default-time="['00:00:00','23:59:59']" @change="dateChange"></el-date-picker>
			</el-form-item>
			<!-- 查询框 -->
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" @click="onSubmit" size="small">搜索</el-button>
			</el-form-item>
		</el-form>
		<el-form :inline="true" :model="query" label-width="130px" size="small">
			<el-form-item label="调整类型：" class="query-form-item">
				<el-select v-model="query.type" placeholder="请选择状态" @change="onSubmit" clearable>
					<el-option label="全部" value=""></el-option>
					<el-option label="充值" value="1"></el-option>
					<el-option label="扣减" value="2"></el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<!-- table表单 -->
		<el-table ref="multipleTable" v-loading="loading" :data="tableData"
			:header-cell-style="{background:'#F4F4F5',color:'#606266'}" border>
			<!-- <el-table-column type="selection" width="55" fixed></el-table-column> -->
			<el-table-column label="序号" type="index" width="80" align="center" fixed>
				<template scope="scope">
					<span>{{(query.currentPage - 1) * query.pageSize + scope.$index + 1}}</span>
				</template>
			</el-table-column>
			<el-table-column label="调整时间" width="180" :show-overflow-tooltip="true" align="center">
				<template slot-scope="scope">
					<i class="el-icon-time" v-if="scope.row.createtime!=null"></i>
					<span
						v-if="scope.row.createtime!=null">{{ scope.row.createtime | formatDateStr('yyyy-MM-dd hh:mm:ss') }}</span>
					<span v-else>无</span>
				</template>
			</el-table-column>
			<el-table-column label="类型" prop="usermobile" align="center" width="150">
				<template slot-scope="scope">
                   <span v-if="scope.row.type == 1">充值</span>
                   <span v-else-if="scope.row.type == 2">扣减</span>
                </template>
			</el-table-column>
			<el-table-column label="调整金额" prop="money" align="center" width="150" />
			<el-table-column label="商城账号" prop="usermobile" align="center" width="150" />
			<el-table-column label="商城企业名称" prop="enterprisename" align="center" width="150" />
			<el-table-column label="社会统一信用码" prop="registrationnumber" align="center" width="150" />
			<el-table-column label="调整前可提现账户" prop="moneyBefore" align="center" width="150" />
			<el-table-column label="调整后可提现账户" prop="moneyAfter" align="center" width="150" />
			<el-table-column label="操作人ID" prop="operator" align="center" width="150" />
			<el-table-column label="备注" prop="remarks" align="center" width="200" fixed="right" />
		</el-table>

		<el-pagination class="pagination-container" background :page-size="query.pageSize"
			@size-change="handleSizeChange" @current-change="handleCurrentChange"
			layout="total,sizes,prev, pager, next, jumper" :current-page="this.query.currentPage"
			:page-sizes="[5,10, 20, 30, 50]" :total="totalNumber">
		</el-pagination>
		</div>
		<!-- 账户调整确定弹窗 -->
		<el-dialog title="提示" :visible.sync="detailVisible" width="40%" top="5vh" :close-on-click-modal="false">
			<template slot="title">
				<div class="avue-crud__dialog__header">
					<span class="el-dialog__title">
						<span style="
                display: inline-block;
                background-color: #3478f5;
                width: 3px;
                height: 20px;
                margin-right: 5px;
                float: left;
                margin-top: 2px;
              "></span>
						确认要发起账户资金调整?
					</span>
				</div>
			</template>
			<el-card>
				<div class="show-msg" style="margin-top:30px'">商城账号：{{this.account.usermobile}}</div>
				<div class="show-msg">企业名称：{{this.account.enterprisename}}</div>
				<div class="show-msg">社会统一信用码：{{this.account.registrationnumber}}</div>
				<div class="show-msg">调整类型：{{this.funds.type == 1?'充值':'扣减'}}</div>
				<div class="show-msg">调整金额：{{this.funds.money}}</div>
			</el-card>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="detailVisible = false">取消</el-button>
				<el-button type="primary" :loading="isEditing" @click.native="edit()">调整</el-button>
			</div>
		</el-dialog>
	</div>

</template>
<script>
	import {
		queryFundChangeHDPage, //获取列表
		setFundAccount, //账户调整
	} from "../../api/fundsManagement/index";
	export default {
		data() {
			const validateMoney = (rule,value,callback) =>{
        if(!value){
            callback(new Error('金额不能为空'))
         }else if(value.split('.').length > 2){
            callback(new Error('输入正确格式的金额')) //防止输入多个小数点
         }else{
            // value = Math.round(value * Math.pow(10,2)) / Math.pow(10,2) //四舍五入
            // value = Number(value).toFixed(2); //不足补位
			function getFloatNumber(num) {
				num += '';
				num = num.replace(/[^0-9|\.]/g, '');
				if (/^0+/) num = num.replace(/^0+/, '');
				if (!/\./.test(num)) num += '.00';
				if (/^\./.test(num)) num = '0' + num;
				num += '00';
				num = num.match(/\d+\.\d{2}/)[0];
				return num;
			}
            this.funds.money =getFloatNumber(value);
            callback();
            }
		};
			return {
				isEditing:false,//是否在修改
				tableData: [], //列表集合
				createTime: [], //时间数组
				pickerOptions: {
					//快速选择日期
					shortcuts: [{
							text: "最近一周",
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(
									start.getTime() - 3600 * 1000 * 24 * 7
								);
								picker.$emit("pick", [start, end]);
							}
						},
						{
							text: "最近一个月",
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(
									start.getTime() - 3600 * 1000 * 24 * 30
								);
								picker.$emit("pick", [start, end]);
							}
						},
						{
							text: "最近三个月",
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(
									start.getTime() - 3600 * 1000 * 24 * 90
								);
								picker.$emit("pick", [start, end]);
							}
						},
						{
							text: "最近六个月",
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(
									start.getTime() - 3600 * 1000 * 24 * 180
								);
								picker.$emit("pick", [start, end]);
							}
						}
					]
				},
				query: {
					currentPage: 1,
					pageSize: 5,
					enterprisename: '',
					startTime: "", //开始时间
					endTime: "", //结束时间
					id: "",
					type:""
				},
				funds:{
					money:'',
					type:1,
					remarks:"",
					userId:''
				},//账户调整
				totalNumber: 0,
				loading: false,
				account:{usermobile:"",enterprisename:"",registrationnumber:"",usersurplusintegral:"",unlimitedaccount:"",limitaccount:""},//从上个页面待会来的数据
				detailVisible:false,//弹窗开关
				rules:{
					type: [
                        { required: true, message: "请选择调整类型", trigger: "blur" },
                    ],
					money: [
						//{ required: true, message: "请输入金额", trigger: "blur" },
						//{ type: 'number', message: '必须为数字值',trigger: 'blur'}
                        {required:true,validator:validateMoney,trigger:'blur' }					],
					remarks:[
						{ required: true, message: "请输入备注", trigger: "blur" }
					]
				 }
			}
		},
		methods: {
			edit(){
				this.isEditing=true
				setFundAccount(this.funds)
							.then((res) => {
								if (res.code != 0) {
									this.$message.error(res.message);
									this.isEditing=false
									return false;
								}
								if(this.funds.type == 1){
									this.account.usersurplusintegral=this.addNum(this.account.usersurplusintegral,this.funds.money)
							    	this.account.unlimitedaccount=this.addNum(this.account.unlimitedaccount,this.funds.money)
								}else{
									this.account.usersurplusintegral-=this.funds.money
							    	this.account.unlimitedaccount-=this.funds.money
								}
								this.$message.success("规则修改成功");
								this.funds.remarks=""
								this.funds.money=""
								this.onSubmit()
								this.detailVisible = false
								setTimeout(() => {
                                  this.isEditing=false
                                }, 0.3*1000)
							})
							.catch((err) => {
                                setTimeout(() => {
                                  this.isEditing=false
                                }, 0.3*1000)
                                this.$message.error(err)
							});
			},
			//账户调整
			editFundRule(formName){

				if(!this.account.userid){
				    this.$message.error('请先选择要调整的账户');
					return false;
		     	}
				if(this.funds.type == 2 && this.funds.money>this.account.unlimitedaccount){
					// console.log(this.funds.type+this.funds.money+this.account.unlimitedaccount)
					 this.funds.money=''
					 this.$message.error('扣减金额超出账户可提现金额');
					 return false;
			    }
				if(this.funds.money==0){
				    this.$message.error('调整金额不能为0');
					return false;
		     	}
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.detailVisible = true
					} else {
						// console.log("error submit!!");
						return false;
					}
				});
			},
			toEntityQuery(){
				this.$router.push('entityQuery')
			},
			/*日期选择事件*/
			dateChange(val) {
				if (val == null) {
					this.query.startTime = "";
					this.query.endTime = "";
				} else {
					this.query.startTime = val[0];
					this.query.endTime = val[1];
					this.query.currentPage = 1;
				}
				this.getList();
				// console.log(this.query);
			},
			// 列表数据获取
			getList() {
				this.loading = true;
				queryFundChangeHDPage(this.query)
					.then(data => {
						// console.log(data)
						if (data.code != 0) {
							this.$message.error(response.message);
							this.loading = false;
							return false;
						}
						this.tableData = data.data.list || []
						this.totalNumber = data.data.totalNumber || 0;
						// console.log(this.tableData)
						setTimeout(() => {
							this.loading = false;
						}, 0.3 * 1000);
					})
					.catch(err => {
						this.loading = false;
						this.tableData = []
					})
			},
           
			//监听一下调整金额的值
			handleMoney(val){
				// console.log(val)
				let temp = val.toString();
				temp = temp.replace(/。/g, ".");
				temp = temp.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
				temp = temp.replace(/^\./g, ""); //验证第一个字符是数字
				temp = temp.replace(/\.{2,}/g, ""); //只保留第一个, 清除多余的
				temp = temp.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
				temp = temp.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
				this.funds.money = temp;

			},
			//查询
			onSubmit() {
				this.query.currentPage = 1;
				this.getList()
				// console.log('submit!');
			},
			handleCurrentChange(val) {
				this.query.currentPage = val;
				//scrollTo(0, 800);
				this.getList()
			},
			handleSizeChange(val) {
				this.query.pageSize = val;
				this.getList()
			},
			/**
			 * 加法运算
			 * @param {Object} arg1
			 * @param {Object} arg2
			 */
			addNum(num1, num2) {
				var sq1, sq2, m;
				try {
					sq1 = num1.toString().split('.')[1].length;
				} catch (e) {
					sq1 = 0;
				}
				try {
					sq2 = num2.toString().split('.')[1].length;
				} catch (e) {
					sq2 = 0;
				}
				m = Math.pow(10, Math.max(sq1, sq2));
				return (num1 * m + num2 * m) / m;

			}
		},

		mounted() {
			this.$nextTick(()=>{
				if(this.$route.query.usermobile){
				this.account=this.$route.query
				this.funds.userId=this.account.userid
				this.query.userId=this.account.userid
			    }
				this.getList()
			})
		},
		created() {
			
		}

	}
</script>
<style scoped>
.el-radio-group .el-radio{
	margin-left: 30px !important	
}
.el-form-item--small /deep/ .el-form-item__error{
	position: absolute;
	padding-top: 4px;
	left:182px;
}
</style>
